<!-- Used by media_constrained_network_perf to record perf metrics. -->
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <title>Constrained Video Test</title>
  </head>

  <body>
    <video controls/>
  </body>

  <script type="text/javascript">
    var video = document.querySelector('video');

    // Tracks time when page load completes and src= is set.
    var loadTime;

    // Tracks time when playback starts.
    var startTime;

    // Metrics to record.  See media_constrained_network_perf for more details.
    // Use -1 to indicate that we haven't recorded these values yet.  The PyAuto
    // controller will poll for these values until they are each >= 0.
    var epp = -1, ttp = -1;

    // Video play progress to calculate percentage of video played.
    var vpp = -1;

    // String to keep track of video events fired.
    var eventsMsg = '';

    // A flag to end the test if error or abort events get fired.
    var endTest = false;

    video.addEventListener('playing', function(event) {
      startTime = new Date().getTime();
      ttp = Math.max(0, startTime - loadTime);
      logEvent(event);
    }, false);

    video.addEventListener('ended', setEPP, false);
    video.addEventListener('error', end, false);

    var events = ['loadstart', 'progress', 'suspend', 'waiting', 'emptied',
                  'stalled', 'play', 'pause', 'loadedmetadata', 'loadeddata',
                  'waiting', 'canplay', 'canplaythrough', 'seeking', 'seeked',
                  'ratechange', 'durationchange', 'volumechange'];

    var len = events.length;
    for (var i = 0; i < len; i++) {
      video.addEventListener(events[i], logEvent, false);
    }

    function end(evt) {
      logEvent(evt);
      endTest = true;
    }

    function logEvent(evt) {
      var d = new Date();
      eventsMsg += d.toLocaleTimeString() + '.' + d.getMilliseconds() + ' ' +
                   evt.target + ' ' + evt.type + ' event fired.\n';
    }

    function setEPP(evt) {
      playTime = new Date().getTime() - startTime;
      durMs = video.duration * 1000;

      epp = Math.max(0, (playTime - durMs) * 100 / durMs);
      logEvent(evt);
    }

    function calculateProgress() {
      if (!isNaN(video.duration))
        vpp = (video.currentTime / video.duration) * 100;

      if (window.domAutomationController)
        window.domAutomationController.send(vpp);
    }

    // Called by the PyAuto controller to initiate testing.
    function startTest(src) {
      loadTime = new Date().getTime();
      epp = ttp = vpp = -1;
      eventsMsg = '';
      endTest = false;

      video.src = src;
      video.play();

      if (window.domAutomationController)
        window.domAutomationController.send(true);
    }
  </script>
</html>
